package com.tenglong.teacher.ui.setting;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.IpUtils;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.cuotibao.zhuoxiao.basics.utils.glide.GlideOptions;
import com.netease.nim.uikit.common.util.string.StringUtil;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.ClientUserInfo;
import com.tenglong.teacher.data.resultInfo.DataState;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.login.LoginSelectOrganizationActivity;
import com.tenglong.teacher.ui.port.MainCallback;
import com.tenglong.teacher.ui.port.MainFragmentRubsh;
import com.tenglong.teacher.ui.dialog.ExitDialog;
import com.tenglong.teacher.ui.login.LoginActivity;
import com.tenglong.teacher.ui.port.MainMessageListener;
import com.tenglong.teacher.ui.setting.setting.ClassRecordActivity;
import com.tenglong.teacher.ui.setting.setting.HelpAndFeedbackActivity;
import com.tenglong.teacher.ui.setting.setting.MessageActivity;
import com.tenglong.teacher.ui.setting.setting.SettingActivity;
import com.tenglong.teacher.ui.setting.setting.VerifyMessageActivity;
import com.tenglong.teacher.ui.utils.StringUtils;
import com.thinkcool.circletextimageview.CircleTextImageView;

import java.io.Serializable;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2018/12/23 0023.
 */

public class FragmentSetting extends Fragment implements MainFragmentRubsh, LSettingItem.OnLSettingItemClick, MainMessageListener, View.OnClickListener {


    public static final String KEY_APP_EXIT = "key_app_exit";
    private CircleTextImageView mHeaderImage;
    private TextView mName, mDetail;
    private Context mContext;
    private LSettingItem messageLayout;
    private int messageNum = 0;
    private LSettingItem mSwitchCharacters;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return LayoutInflater.from(getContext()).inflate(R.layout.fragment_setting, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        setListeners(view);
        initData();
    }

    private void initData() {
        setUserDetail();
        setHeaderImage();
        setUserName();
        requestRedPointInfo();
    }

    private void setListeners(View view) {
        ((LSettingItem) view.findViewById(R.id.mVersion)).setmOnLSettingItemClick(this);
        ((LSettingItem) view.findViewById(R.id.mExit)).setmOnLSettingItemClick(this);
        ((LSettingItem) view.findViewById(R.id.mSetting)).setmOnLSettingItemClick(this);
        ((LSettingItem) view.findViewById(R.id.mAboutUs)).setmOnLSettingItemClick(this);
        ((LSettingItem) view.findViewById(R.id.mAddTickling)).setmOnLSettingItemClick(this);
        ((LSettingItem) view.findViewById(R.id.classRecord)).setmOnLSettingItemClick(this);
        mSwitchCharacters.setmOnLSettingItemClick(this);
        messageLayout.setmOnLSettingItemClick(this);
        ((LSettingItem) view.findViewById(R.id.mHelp)).setmOnLSettingItemClick(this);
        mHeaderImage.setOnClickListener(this);
    }

    private void initView(View view) {
        mHeaderImage = view.findViewById(R.id.mHeaderImage);
        mName = view.findViewById(R.id.mName);
        mDetail = view.findViewById(R.id.mDetail);
        messageLayout = view.findViewById(R.id.mInform);
        mSwitchCharacters = view.findViewById(R.id.mSwitchCharacters);
        List<ClientUserInfo> userInfos = DataState.getInstance().getUserInfos();
        mSwitchCharacters.setVisibility(userInfos == null || userInfos.size() <= 1 ? View.GONE : View.VISIBLE);
    }


    private void setHeaderImage() {
        ClientUserInfo userInfo = DataState.getInstance().getUserInfo();
        RequestOptions options = GlideOptions.getGlideRequestOptions().
                error(R.drawable.setting_image_defauft_header).
                placeholder(R.drawable.header_image_loading);
        Glide.with(this)
                .load(IpUtils.getImageUrl(userInfo.getPhotoUrl()))
                .apply(options)
                .into(mHeaderImage);
    }

    private void setUserDetail() {
        ClientUserInfo userInfo = DataState.getInstance().getUserInfo();
        mDetail.setVisibility(TextUtils.isEmpty(userInfo.getSlogan()) ? View.GONE : View.VISIBLE);
        if (mDetail.getVisibility() == View.VISIBLE) {
            mDetail.setText(StringUtil.replaceBlank(userInfo.getSlogan()));
        }
    }

    private void setUserName() {
        ClientUserInfo userInfo = DataState.getInstance().getUserInfo();
        mName.setVisibility(TextUtils.isEmpty(userInfo.getUserName()) ? View.GONE : View.VISIBLE);
        if (mName.getVisibility() == View.VISIBLE) {
            mName.setText(userInfo.getUserName());
        }
    }


    private void requestRedPointInfo() {
        CreateRequestEntity.getWebService().getUnreadMessageNumber().enqueue(new Callback<BaseResult<Integer>>() {
            @Override
            public void onResponse(Call<BaseResult<Integer>> call, Response<BaseResult<Integer>> response) {
                if (ResultVerifier.isSucceed(response)) {
                    messageNum = response.body().data;
                    setRedPoint(messageNum);
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<Integer>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
            }
        });
    }


    private void setRedPoint(int pointNumber) {
        messageLayout.setRedPoint(pointNumber);
        ((MainCallback) mContext).onUserRedPoint(pointNumber > 0);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case GlobalConstant.REQUEST_CODE_USER_DETAIL:
                    initData();
                    break;
                case GlobalConstant.REQUEST_CODE_MESSAGE_ACTIVITY:
                    if (data != null) {
                        messageNum = data.getIntExtra(VerifyMessageActivity.KEY_VERIFY_MESSAGE_NUMBER, 0);
                    }
                    setRedPoint(messageNum);
                    break;
                case GlobalConstant.REQUES_CODE_LOGIN_SELECT_ORGANIZATION_ACTIVITY:
                    initData();
                    break;
            }
        }
    }


    @Override
    public void refresh() {
        initData();
    }

    @Override
    public void skipVerifyMessage() {
        if (isAdded() && messageLayout != null) {
            Intent intent = new Intent(mContext, MessageActivity.class);
            intent.putExtra(MessageActivity.KEY_MESSAGE_DIRECTION, MessageActivity.VERIFY_MESSAGE_DIRECTION);
            intent.putExtra(MessageActivity.KEY_MESSAGE_NUMBER, messageNum);
            startActivityForResult(intent, GlobalConstant.REQUEST_CODE_MESSAGE_ACTIVITY);
        }
    }

    @Override
    public void click(View view, boolean isChecked) {
        switch (view.getId()) {
            case R.id.mVersion:
            case R.id.mSetting:
            case R.id.mAboutUs:
            case R.id.mAddTickling:
            case R.id.mExit:
            case R.id.classRecord:
            case R.id.mInform:
            case R.id.mSwitchCharacters:
                onClick(view);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mSetting:
                startActivity(new Intent(mContext, SettingActivity.class));
                break;
            case R.id.mAboutUs:
                startActivity(new Intent(mContext, VersionActivity.class));
                break;
            case R.id.mInform:
                Intent intent = new Intent(mContext, MessageActivity.class);
                intent.putExtra(MessageActivity.KEY_MESSAGE_NUMBER, messageNum);
                startActivityForResult(intent, GlobalConstant.REQUEST_CODE_MESSAGE_ACTIVITY);
                break;
            case R.id.classRecord:
                startActivity(new Intent(mContext, ClassRecordActivity.class));
                break;
            case R.id.mAddTickling:
                startActivity(new Intent(mContext, HelpAndFeedbackActivity.class));
                break;
            case R.id.mHeaderImage:
                startActivityForResult(new Intent(mContext, UserDetailsActivity.class), GlobalConstant.REQUEST_CODE_USER_DETAIL);
                break;
            case R.id.mExit:
                ExitDialog.getExitDialog(getString(R.string.setting_text_exit_tip)).setExitListener(new ExitDialog.ExitListener() {
                    @Override
                    public void onExit(boolean exitState) {
                        if (exitState) {
                            DataState.getInstance().appExit();
                            SharedPreferences.Editor editor = mContext.getSharedPreferences("preference", 0).edit();
                            editor.putBoolean(StringUtils.USER_LOGIN_STATE, false);
                            editor.commit();
                            Intent i = new Intent(mContext, LoginActivity.class);
                            i.putExtra(KEY_APP_EXIT, "1");
                            startActivity(i);
                            ((Activity) mContext).finish();
                        }
                    }
                }).show(getChildFragmentManager(), "dialog");
                break;
            case R.id.mSwitchCharacters:
                Intent switchOrganizationIntent = new Intent();
                switchOrganizationIntent.setClass(mContext, LoginSelectOrganizationActivity.class);
                switchOrganizationIntent.putExtra(LoginSelectOrganizationActivity.KEY_SWITCH_ORGANIZATION_TYPE, LoginSelectOrganizationActivity.TYPE_USER_SWITCH_ORGANIZATION);
                switchOrganizationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivityForResult(switchOrganizationIntent, GlobalConstant.REQUES_CODE_LOGIN_SELECT_ORGANIZATION_ACTIVITY);
                break;
        }
    }
}
